package com.ants.boot.core.security.provider;

import com.ants.boot.core.security.service.CustomUserDetailsServiceImpl;
import com.ants.boot.core.security.token.CustomAuthenticationToken;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author 蚂蚁会花呗
 * @date 2022/10/9 9:25
 * 传统用户名密码认证器
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CustomUserDetailsServiceImpl customUserDetailsService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        logger.info("账号密码验证开始！");
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();
        if (StringUtils.isBlank(username)){
            logger.error("账号不能为空！");
            throw new BadCredentialsException("账号不能为空！");
        }
        if (StringUtils.isBlank(password)){
            logger.error("密码不能为空！");
            throw new BadCredentialsException("验证码不能为空！");
        }
        UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean isMatch = encoder.matches(password, userDetails.getPassword());
        if (!isMatch){
            logger.info("密码校验失败！");
            throw new BadCredentialsException("密码错误,请重新输入");
        }
        return new CustomAuthenticationToken(userDetails, null,userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        boolean res = CustomAuthenticationToken.class.isAssignableFrom(authentication);
        return res;
    }
}
